package com.example.wc;

/**
 *
 *  * @projectName myflinkstu
 *  * @title     StreamWordCount
 *  * @package    com.example.wc
 *  * @description    WordCount
 *  * @author hjx
 *  * @date   2022-3-17 14:27
 *  * @version V1.0.0
 *  * @copyright 2022 ty
 *
 */

import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.runtime.state.filesystem.FsStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class StreamWordCount {
    public static void main(String[] args) throws Exception {
        // 创建流处理执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
//        env.setParallelism(1); // 设置并行数，默认是跟服务器核数相同
//        env.disableOperatorChaining(); // 所有任务不参加任务链的合并操作（多个人物之间不合并）

//        // 从文件中读取数据
//        String inputPath = "D:\\IDEAProject\\flinkDemo\\FlinkTutorial\\src\\main\\resources\\hello.txt";
//        DataStream<String> inputDataStream = env.readTextFile(inputPath);

        //1.1 开启CK并指定状态后端为FS    memory  fs  rocksdb
        env.setStateBackend(new FsStateBackend("hdfs://cdh1:8020/ideapro/myflinkstu/ck"));
        env.enableCheckpointing(5000L);
        env.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);
        env.getCheckpointConfig().setCheckpointTimeout(10000L);
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000);


        // 用parameter tool工具从程序启动参数中提取配置项

//        ParameterTool parameterTool = ParameterTool.fromArgs(args);
//        String host = parameterTool.get("host");
//        int port = parameterTool.getInt("port");

        // 从socket文本流读取数据
        DataStream<String> inputDataStream = env.socketTextStream("10.105.2.140", 7777);


        // 基于数据流进行转换计算
//        DataStream<Tuple2<String, Integer>> resultStream = inputDataStream
//                .flatMap(new WordCount.MyFlatMapper()).slotSharingGroup("green")
//                .keyBy(0)
//                .sum(1).setParallelism(2).slotSharingGroup("red") // .slotSharingGroup("red"); 设置 slot 共享组
//                .disableChaining()  //.disableChaining() 即sum()不参加任务链的合并操作（多个人物之间不合并）
//                 .startNewChain();  // 即后面操作重新开始一个新任务，可以合并
//
//        resultStream.print().setParallelism(1);

        DataStream<Tuple2<String, Integer>> resultStream = inputDataStream
                .flatMap(new WordCount.MyFlatMapper())
                .keyBy(0)
                .sum(1);

        resultStream.print();
        // 执行任务
        env.execute();
    }
}

